<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('主体类型')" prop="investorType">
            <dictSelect
              v-model="form.investorType"
              :clearable="true"
              dictionary="deal_investment_type"
              :disabled="form.id !== undefined"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('主体名称')" prop="investorId">
            <MainBodySelect
              v-model="form.investorId"
              :parameters="form.investorType"
              :disabled="form.id !== undefined"
              @change="getCurrencyByInvestorId($event)"
            />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('SPV')" prop="spvId">-->
        <!--            <spv-select v-model="form.spvId" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="12">
          <el-form-item :label="$t('预计投资时间')" prop="dateInvestmentEstimate">
            <DatePicker v-model="form.dateInvestmentEstimate" :placeholder="$t('预计投资时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计投资金额') + $t('金额单位')" prop="amountInvestmentEstimate">
            <money v-model="form.amountInvestmentEstimate" unit="w" :placeholder="$t('预计投资金额')" />
          </el-form-item>
        </el-col>
        <el-col v-if="this.$route.query.dealType === 'equity'" :span="12">
          <el-form-item :label="$t('进入时持股比例(%)')">
            <Ratio
              v-model="form.initialShareholdingRatio"
              :max="100"
              :controls="false"
              :placeholder="$t('进入时持股比例(%)')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="this.$route.query.dealType !== 'bf'" :label="$t('最新持股比例(%)')">
            <Ratio
              v-model="form.latestShareholdingRatio"
              :max="100"
              :controls="false"
              :placeholder="$t('最新持股比例(%)')"
            />
          </el-form-item>
          <el-form-item v-else :label="$t('认缴比例(%)')">
            <Ratio
              v-model="form.latestShareholdingRatio"
              :max="100"
              :controls="false"
              :placeholder="$t('认缴比例(%)')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('主体币种')" prop="currency">
            <span v-if="form.investorType === 'fund' || form.investorType === 'spv'" slot="label">
              {{ $t('主体币种') }}
              <el-tooltip :content="$t('自动带出选中的主体币种')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-select v-model="form.currency" :placeholder="$t('币种')">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="investmentSignTime">
            <span slot="label">
              {{ $t('投资协议签署时间') }}
              <el-tooltip :content="$t('第一个审批通过的投资协议的签署时间')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <DatePicker v-model="form.investmentSignTime" :placeholder="$t('第一个审批通过的投资协议的签署时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="dateInvestmentFact">
            <span slot="label">
              {{ $t('首次划款时间') }}
              <el-tooltip :content="$t('第一笔项目划款的时间')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <DatePicker v-model="form.dateInvestmentFact" :placeholder="$t('第一笔项目划款的时间')" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.id !== undefined && this.$route.query.dealType === 'equity'" :span="12">
          <el-form-item prop="agreementMoney">
            <span slot="label">
              {{ $t('协议金额') }} {{ $t('金额单位') }}
              <el-tooltip :content="$t('审批完成并且类型为投资协议的合同金额汇总, 以主体币种展示')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.agreementMoney" :placeholder="$t('审批完成并且类型为投资协议的合同金额汇总, 以主体币种展示')" unit="w" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col v-if="this.$route.query.dealType === 'equity'" :span="12">
          <el-form-item :label="$t('投资角色')" prop="investmentRole">
            <dictSelect
              v-model="form.investmentRole"
              :clearable="true"
              dictionary="deal_investment_role"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.id && this.$route.query.dealType === 'equity'" :span="24">
          <el-divider content-position="left">{{ $t('以下金额按项目币种') }}<span style="color: #1890ff">{{ formatCurrency(tempCurrency) }}</span>{{ $t('展示') }}</el-divider>
        </el-col>
        <el-col v-if="form.id !== undefined" :span="12">
          <el-form-item prop="agreementMoneyInvest">
            <span slot="label">
              {{ $t('协议金额') }}  {{ $t('金额单位') }}
              <el-tooltip :content="$t('审批完成并且类型为投资协议的合同金额汇总, 以项目币种展示')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.agreementMoneyInvest" :placeholder="$t('审批完成并且类型为投资协议的合同金额汇总, 以项目币种展示')" unit="w" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.id !== undefined && this.$route.query.dealType === 'equity'" :label="$t('持股数量') + $t('(万股)')" prop="numberOfShares">
            <money v-model="form.numberOfShares" unit="w" disabled :placeholder="$t('持股数量')" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.id !== undefined" :span="12">
          <el-form-item>
            <span slot="label">
              {{ $t('实际投资金额') }} {{ $t('金额单位') }}
              <el-tooltip :content="$t('审批已经通过的项目划款金额汇总')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.amountInvestmentFact" unit="w" :placeholder="$t('审批已经通过的项目划款金额汇总')" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.id !== undefined" :span="12">
          <el-form-item>
            <span slot="label">
              {{ $t('已回款金额') }} {{ $t('金额单位') }}
              <el-tooltip :content="$t('现金流(所有流入的实际现金金额)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="xjl.hk" unit="w" :placeholder="$t('已回款金额')" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.id !== undefined" :span="12">
          <el-form-item>
            <span slot="label">
              {{ $t('已回收本金') }} {{ $t('金额单位') }}
              <el-tooltip :content="$t('现金流(所有流入并且类型为本金的实际现金金额)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="xjl.hkbj" unit="w" :placeholder="$t('已回收本金')" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.id !== undefined" :span="12">
          <el-form-item>
            <span slot="label">
              {{ $t('已回款收益') }} {{ $t('金额单位') }}
              <el-tooltip :content="$t('现金流(所有流入并且类型为收益的实现现金金额)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="xjl.hksy" unit="w" :placeholder="$t('已回款收益')" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.id !== undefined" :span="12">
          <el-form-item>
            <span slot="label">
              {{ $t('最新估值') }} {{ $t('金额单位') }}
              <el-tooltip :content="$t('现金流(参与IRR计算并且类型为估值的现金流金额)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="xjl.gz" unit="w" :placeholder="$t('最新估值')" :disabled="true" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.id !== undefined" :span="12">
          <el-form-item>
            <span slot="label">
              {{ $t('最新IRR(%)') }}
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-html="$t('根据现金流自动计算<br>')" />
                  <span v-html="$t('错误情况:<br>')" />
                  <span v-html="$t('502:小于或等于一条现金流<br>')" />
                  <span v-html="$t('503:第一条现金流的时间不是最早时间<br>')" />
                  <span v-html="$t('504:第一条现金流的payment的值不为负')" />
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <div style="display: flex;">
              <el-input-number v-model="form.latestIrr" :disabled="true" :controls="false" :placeholder="$t('根据现金流自动计算')" />
              <el-button slot="append" @click="findHistoryIRR(form)">{{ $t('查看历史') }}</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" has-permi="deal:investment" data-type="deal_investment" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="deal:investment" />
    </div>

    <!-- 现金流IRR对话框 -->
    <el-dialog v-loading="irrLoading" :title="$t('历史业绩')" :visible.sync="irrOpen" custom-class="customDialog" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <el-table v-loading="irrLoading" :data="dealIrrList" border max-height="600" class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('维度')" align="center" prop="dimension" min-width="259" />
        <el-table-column :label="$t('IRR')" align="center" prop="xirr" width="200">
          <template slot-scope="scope">
            <span><el-link type="primary" @click="findXIrrDetails(scope.row)">{{ moneyFormat(scope.row.xirr, undefined, 2, true) }}</el-link></span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('MOIC')" align="center" prop="moic" min-width="200" />
      </el-table>
    </el-dialog>

    <!-- xIrr计算明细对话框 -->
    <el-dialog :title="$t('计算明细')" :visible.sync="xIrrDetailsOpen" :close-on-click-modal="false" :lock-scroll="false" :width="'50%'" custom-class="customDialog" append-to-body>
      <xIrrBaseDetailsList ref="xIrrBaseDetailsList" class="dialog-content" />
      <div slot="footer" class="dialog-footer mt-15" style="text-align: right;">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportXIrrHandle"
        >{{ $t('导出') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import { saveDealInvestment, getDealInvestment, getCashFlow, getDealInvestmentIrrHistory } from '@/api/deal/investment/dealInvestment'
    import { getBusById } from '@/api/file/fileBase'
    import MainBodySelect from '@/components/MainBodySelect/index'
    import xIrrBaseDetailsList from '@/components/Xirr/details/xirrBaseDetailsList'
    // import SpvSelect from '@/components/Select/SpvSelect.vue'
    export default {
      components: {
        MainBodySelect,
        xIrrBaseDetailsList
        // SpvSelect
      },
        data() {
          return {
            otherBtnHide: false,
            // 币种字典
            currencyOptions: [], // 表单参数
            form: {
              investorType: '',
              // 附件列表
              fileList: []
            },
            xjl: {
              hk: undefined,
              hkbj: undefined,
              hksy: undefined,
              gz: undefined
            },
            // 遮罩层
            loading: false,
            irrLoading: false,
            // 表单校验
            rules: {
              investorId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
              investorType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
              // dateInvestmentEstimate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
              // amountInvestmentEstimate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
              currency: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
            },
            tempCurrency: '',
            dealIrrList: [],
            irrOpen: false,
            xIrrDetailsOpen: false
          }
        },
      watch: {
        'form.investorType': {
          handler(val) {
            if (val && !this.form.id) {
              console.log(val, this.form.investorType, 'form.investorType')
              this.form.investorId = undefined
            }
          }
        }
      },
        created() {
            this.getDicts('currency').then(response => {
                this.currencyOptions = response.data
            })
            getBusById(this.form.dealId ? this.form.dealId : this.$route.query.id).then(res => {
              if (res.data !== null && res.data.currency !== null) {
                this.tempCurrency = res.data.currency
              }
            })
        },
        methods: {
            // 初始化数据
            init(data) {
                if (data != null && data.id !== undefined) {
                  this.loading = true
                  getDealInvestment(data.id).then(response => {
                    this.form = response.data
                    // 获取现金流的几个字段
                    this.getCashFlow(this.form.investorId, this.form.dealId)
                    this.loading = false
                  })
                } else {
                    this.reset()
                }
            },
            getCashFlow(investorId, dealId) {
              getCashFlow(investorId, dealId).then(response => {
                console.log(response)
                if (response.data !== null) {
                  this.xjl = response.data
                }
              })
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                dealId: this.$route.query.id,
                investorId: undefined,
                investorName: undefined,
                investorType: '',
                spvId: undefined,
                currency: '',
                dateInvestmentEstimate: undefined,
                amountInvestmentEstimate: undefined,
                dateInvestmentFact: undefined,
                amountInvestmentFact: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                fileList: [],
                remark: undefined,
                delFlag: undefined,
                latestShareholdingRatio: undefined,
                initialShareholdingRatio: undefined,
                investmentSignTime: undefined,
                agreementMoney: undefined,
                agreementMoneyInvest: undefined,
                numberOfShares: undefined,
                investmentRole: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                if (this.$parent.$parent.investorOpen !== undefined) {
                  this.$parent.$parent.investorOpen = false
                }
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                if (this.$parent.$parent.investorOpen !== undefined) {
                  this.$parent.$parent.investorOpen = false
                }
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            // 根据主体的id获取币种
            getCurrencyByInvestorId(id) {
              getBusById(id).then(response => {
                if (response.data !== null && response.data.currency !== undefined && response.data.curr !== null) {
                  this.form.currency = response.data.currency
                }
              })
            },
            formatCurrency(val) {
              const currency = this.currencyOptions.find(obj => obj.dictValue === val)
              if (currency) {
                return currency.dictLabel
              }
              return val
            },
            /** 提交按钮 */
            submitForm: function() {
              this.$refs['form'].validate(valid => {
                if (valid) {
                  this.loading = true
                  saveDealInvestment(this.form).then(response => {
                    if (response.code === 200) {
                      this.msgSuccess(this.$t('保存成功'))
                      this.closeForm()
                    } else {
                      this.msgError(response.msg)
                      this.loading = false
                    }
                  }).catch(() => {
                    this.loading = false
                  })
                } else {
                  this.locationError(document)
                }
              })
           },
          findHistoryIRR(data) {
            this.irrOpen = true
            this.irrLoading = true
            this.dealIrrList = []
            getDealInvestmentIrrHistory(data).then(response => {
              this.dealIrrList = response.rows
            })
            this.irrLoading = false
          },
          findXIrrDetails(row) {
            this.xIrrDetailsOpen = true
            this.$nextTick(() => {
              this.$refs.xIrrBaseDetailsList.init(row.id)
            })
          },
          exportXIrrHandle() {
            this.$nextTick(() => {
              this.$refs.xIrrBaseDetailsList.exportHandle()
            })
          }

        }

    }
</script>

<style lang="scss" scoped>
/deep/.customDialog .el-dialog__body {
  height: 48vh;
  overflow-y: auto;
  .list-table {
    margin: -20px;
  }
}
</style>
